package com.example.book.interceptor;

import com.example.book.constant.Constants;
import com.example.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.catalina.User;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-12-16
 * Time: 19:11
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        true 表示放行  false表示拦截
        log.info("LoginInterceptor preHandle");
        /*
         * 第一种写法
         * 系统不会自动生成一个会话，，
         * 也没有对userInfo的进一步验证
         * 只是简单的获取它*/
//        获取session，默认值为true，我们设置为false
//        HttpSession session = request.getSession(false);
//        if(session == null){
//            return false;
//        }
//        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);//获取到的类型是Object类型向下转型

        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);//获取到的类型是Object类型向下转型
        if(userInfo == null || userInfo.getId() <= 0){
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
